package com.villaday.idf.activity;

import android.os.Handler;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.Sms;
import com.villaday.idf.model.SmsEntity;
import com.villaday.idf.model.members;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/*绑定/修改手机号
* */
public class BindPhoneActivity extends BaseActivity implements OkHttpUtil.OnDataListener {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.tv_nowPhone)
    TextView tvNowPhone;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_identify)
    TextView tvIdentify;
    @BindView(R.id.tv_change)
    TextView tvChange;

    @BindView(R.id.tv_bind)
    TextView tvBind;
    private int type;//0为绑定1为修改

    private final int retryLimit = 120;//重试秒数上限
    private int timeNum = retryLimit;//获取验证码倒计时
    private long getCodeTime;//获取到验证码的时间
    private boolean isRegister;//是否正在注册
    private String correctCode;//正确的验证码
    private String mobile;//获取验证码的手机号
    private Gson gson = new GsonBuilder().create();
    private Handler handler = new Handler();
    private RefreshtokenEntity refreshtoken;

    private LoadingDialog loadingDialog;


    @Override
    protected int getViewResId() {
        return R.layout.activity_bind_phone;
    }

    @Override
    protected void init() {

    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map, this);
    }

    @OnClick({R.id.tv_identify, R.id.tv_bind, R.id.tv_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_identify://获取验证码
                getCode();
                break;
            case R.id.tv_bind: {//绑定
                String phone = etPhone.getText().toString();
                String code = etCode.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.initToast(this, "请输入手机号");
                } else if (TextUtils.isEmpty(code)) {
                    ToastUtil.initToast(this, "请输入短信验证码");
                } else {
                    loadingDialog = LoadingDialog.newInstance("绑定中...");
                    loadingDialog.show(getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    OkHttpUtil.postJson(this, Constant.URL.members, new members(1, phone, code), map, this);
                }
                break;
            }
            case R.id.tv_change://修改
                String phone = etPhone.getText().toString();
                String code = etCode.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.initToast(this, "请输入手机号");
                } else if (TextUtils.isEmpty(code)) {
                    ToastUtil.initToast(this, "请输入短信验证码");
                } else {
                    loadingDialog = LoadingDialog.newInstance("修改中...");
                    loadingDialog.show(getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    OkHttpUtil.postJson(this, Constant.URL.members, new members(2, phone, code), map, this);
                }
                break;
        }

    }


    //获取验证码
    private void getCode() {
        if (tvIdentify.isSelected()) {
            String mobile = etPhone.getText().toString();
            if (mobile.length() == 0) {
                ToastUtil.initToast(this, "手机号码不能为空");
            } else if (!mobile.matches(Constant.Strings.RegexMobile)) {
                ToastUtil.initToast(this, "请输入正确的手机号码");
            } else {
                tvIdentify.setSelected(false);
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(this, Constant.URL.sms, new Sms(402, mobile), map, this);
                //设置XX秒后重试
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (tvIdentify != null) {
                            tvIdentify.setText("点击重新发送 (" + timeNum + ")");
                            if (timeNum > 0) {
                                handler.postDelayed(this, 1000);
                                timeNum--;
                            } else {
                                tvIdentify.setText("获取验证码");
                                timeNum = retryLimit;
                                if (etPhone.getText().length() == 11) {
                                    etCode.setSelected(true);
                                }
                            }
                        }
                    }
                });

            }
        } else {
            ToastUtil.initToast(this, "请先输入手机号");
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                LogeUtil.e("refresh_token", json);
                refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                    //改变 主页bottom vip 图标及文字颜色
                    mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor),refreshtoken.getBody().getMember().getType());

                    SharedPreferencesUtil.saveRoleInfo(this, json);
                    SharedPreferencesUtil.saveToken(this, refreshtoken.getBody().getToken());
                    UpdateUI(refreshtoken.getBody().getMember());
                } else {
                    ToastUtil.initToast(this, refreshtoken.getMsg());
                }
            } else if (Constant.URL.members.equals(url)) { //绑定手机号
                dismissLoading();
                LogeUtil.e("members", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    ToastUtil.initToast(this, se.getMsg());
                    getData();
                    finish();
                } else {
                    ToastUtil.initToast(this, se.getMsg());
                }
            } else if (Constant.URL.sms.equals(url)) { //刷新Token
                LogeUtil.e("sms", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    ToastUtil.initToast(this, se.getMsg());
                } else {
                    ToastUtil.initToast(this, se.getMsg());
                }
            }
        }

    }


    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    private void UpdateUI(RefreshtokenEntity.BodyBean.MemberBean d) {
        if (!TextUtils.isEmpty(d.getMobile())) {
            type = 1;
            tvNowPhone.setVisibility(View.VISIBLE);
            tvChange.setVisibility(View.VISIBLE);
            tvBind.setVisibility(View.GONE);
            etPhone.setHint("修改你的手机号码");
            tvNowPhone.setText("当前手机号：" + d.getMobile());
            ToolBarUtil.initToolBar(toolbarText, "修改手机号", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        } else {
            tvNowPhone.setVisibility(View.GONE);
            tvChange.setVisibility(View.GONE);
            tvBind.setVisibility(View.VISIBLE);
            etPhone.setHint("绑定你的手机号");
            ToolBarUtil.initToolBar(toolbarText, "绑定手机号", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);

        }

    }

    //门店手机号判断输入是否正确
    @OnTextChanged(value = R.id.et_phone, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void etStoreMobileChanged(CharSequence text) {
        PhoneUtil.isEditError2(text.toString(), etPhone);
        if (text.length() == 11 && text.toString().matches(Constant.Strings.RegexMobile)) {
            tvIdentify.setSelected(true);
            tvIdentify.setClickable(true);
        } else {
            tvIdentify.setClickable(false);
            tvIdentify.setSelected(false);

            tvIdentify.setText("获取验证码");
            handler.removeCallbacksAndMessages(null);
            timeNum = retryLimit;
            isRegister = false;
            correctCode = "";
            mobile = "";
            getCodeTime = 0;

        }
        if (text.length() == 11 && text.toString().matches(Constant.Strings.RegexMobile) && etCode.getText().toString().length() >= 4) {
            tvChange.setSelected(true);
        } else {
            tvChange.setSelected(false);
        }
    }


    //门店手机号判断输入是否正确
    @OnTextChanged(value = R.id.et_code, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void etCodeChanged(CharSequence text) {
        PhoneUtil.isEditError2(text.toString(), etCode);
        if (etPhone.getText().toString().length() == 11 && etPhone.getText().toString().matches(Constant.Strings.RegexMobile) && text.toString().length() >= 4) {
            tvChange.setSelected(true);
        } else {
            tvChange.setSelected(false);
        }
    }
}
